<template>
  <div class="send-sms" id="smsWrapPane">
        <h3>{{$t('sms.sendSms')}}
          <el-tooltip class="item" effect="dark" :content="$t('sms.smsWarnText', {smsSplitNum: smsSplitNum})" placement="right">
            <span class="icon-question"></span>
          </el-tooltip>
        </h3>
        <div class="input-wrap">
          <input type="text" v-model="form.smsPhoneNum" @keyup.enter="sendSms" @keyup="keyUpSmsInput" :placeholder="$t('sms.enterYourPhone')">
          <span class="send-btn" :class="[sendingState ? 'disabled-btn' : '']" @click.stop="sendSms">{{$t('email.send')}}</span>
        </div>
        <p>{{$t('sms.choiseTemplte')}}</p>
        <template>
          <el-select size="mini" filterable v-model="selectedsms" :placeholder="$t('public.pleasePick')" @change="changeout">
            <el-option
              class="sms-select-option"
              v-for="item in smsTemplates"
              :key="item._id"
              :label="item.displayname"
              :value="item.num">
              <b class="sms-title-b">{{ item.name }}:</b> <span>{{item.content}}</span>
            </el-option>
          </el-select>
        </template>
        <div class="warp-pre" id="smsContentPane" v-if="cursmstemplate && cursmstemplate.contented" v-html="cursmstemplate.contented">
        </div>
        <p class="warp-pre sign-name" v-if="cursmstemplate && cursmstemplate.signname">{{cursmstemplate.signname}}</p>
        <p class="warn-text" v-html="$t('sms.reciprocalNum')"></p>
        <p class="warn-text2" v-html="$t('sms.smsPagingNum')"></p>
        <el-checkbox v-model="closedSms" class="smscheck-btn">{{$t('sms.afterSendClose')}}</el-checkbox><br>
        <el-button @click.stop="reset" class="sms-reset primary_btn">{{$t('public.reset')}}</el-button>
        <el-button type="primary" @click.stop="closeSms" class="sms-closed primary_btn">{{$t('webchat.close')}}</el-button>
      </div>
</template>
<script>
  // 此组件为电话条短信气泡弹出组件
  import {matchingOperator, phoneFilterChats, checkHideTel, replaceHtmlToStr} from '@/utils/m7Utils'
  let form = {
    smsPhoneNum: '',
    cursmsontent: ''
  }
  export default {
    name: 'SmsPopover',
    props: {
      isSmsTemplate: {type: Number, default: 0}
    },
    watch: {
      isSmsTemplate () {
        this.getSmsTemplate()
      }
    },
    data () {
      return {
        // smsvisible: false, // 无用多余代码，稳定后可删除
        form: {
          smsPhoneNum: '',
          smsTemplateVar1: '',
          smsTemplateVar2: '',
          value: ''
        },
        smsSplitNum: this.$store.state.session.account.smsSplitBaseNum || 66, // 每条短信的长度 计费配置：账号配置 =》 产品 =》 呼叫中心 =》 查看/设置
        smsChannels: [], // 短信通道配置
        maxWordNum: 280, // 短信字数限制 计费配置：账号配置 =》 产品 =》 呼叫中心 =》 短信设置
        selectedsms: '', // 当前被选中的短信模板
        smsTemplates: '', // 当前账户的配置的所有短信模板
        cursmstemplate: '', // 当前短信模板
        closedSms: true, // 发送后是否关闭弹窗，默认关闭
        realSmsNum: '', // 解决号码隐藏功能之后，其他模块带到短信的号码没有隐藏
        sendingState: false // 是否正在发送短信的标志
      }
    },
    updated () {
      this.updateSmsNum()
      // if (this.smsvisible) { // 无用多余代码，稳定后可删除
      //   let pane = document.getElementById('auto_complete_dialout')
      //   if (pane) {
      //     let inputNode = pane.getElementsByClassName('el-input__inner')[0]
      //     if (inputNode) {
      //       inputNode.focus()
      //     }
      //   }
      // }
    },
    methods: {
      getSmsTemplate () { // 点击短信icon时获取短信的模板
        let megNum = this.$store.state.call.transCache.megNum
        if (megNum) {
          this.form.smsPhoneNum = megNum
        }
        this.realSmsNum = this.form.smsPhoneNum || ''
        this.form.smsPhoneNum = checkHideTel(this.form.smsPhoneNum, this.$store.state.session.user)
        this.$store.dispatch('getSelectSms').then((smsselsect) => {
          if (smsselsect) {
            this.smsTemplates = smsselsect
          }
        })
      },
      closeSms () { // 点击关闭按钮的时候
        this.$emit('smsWindowSatus', false)
        this.form.smsPhoneNum = ''
        this.$store.commit('call/SET_CALL_NUM', '')
      },
      showSmsPopover () {
        this.$emit('smsWindowSatus', true)
      },
      keyUpSmsInput () { // realSmsNum置空，realSmsNum是为解决号码隐藏功能之后，其他模块带到短信的号码没有隐藏，号码输入框变动时取客户自己输入的号码
        this.realSmsNum = ''
      },
      sendSms () {
        if (this.sendingState === true) { // 发送短信的请求还没回来之前，不能再次发送短信（之前有客户报每个月短信消耗量比之前翻倍）
          return
        }
        if (!this.selectedsms) {
          this.$message.error(this.$t('sms.chooseTempToSend'))
          return false
        }
        // realSmsNum解决号码隐藏功能之后，其他模块带到短信的号码没有隐藏
        let sendphone = this.realSmsNum || this.form.smsPhoneNum
        let pane = document.getElementById('smsContentPane')
        let nodeList = pane.getElementsByClassName('smsTemplateVar')
        let committmpl = {}
        committmpl.operatorStrategy = this.cursmstemplate.operatorStrategy
        committmpl.content = this.cursmstemplate.content
        committmpl.sendType = 'template'
        committmpl.num = sendphone
        committmpl.templateid = this.cursmstemplate._id
        committmpl.template = committmpl.content
        committmpl.vars = nodeList.length
        committmpl.templateSign = this.cursmstemplate.templateSign
        let smsChannelLen = 0
        if (this.cursmstemplate.smsChannel) {
          smsChannelLen = this.cursmstemplate.smsChannel.length
        }
        if (committmpl.operatorStrategy) {
          let param = matchingOperator(sendphone)
          committmpl.smsChannel = this.cursmstemplate[param]
        } else if (smsChannelLen > 0) {
          committmpl.smsChannel = this.cursmstemplate.smsChannel[0]
        } else {
          this.$message.error(this.$t('sms.channelerror'))
          return
        }
        for (let i = 0; i < nodeList.length; i++) {
          let j = i + 1
          committmpl['smsTemplateVar' + j] = this.delSpecialChar(nodeList[i].innerText)
          committmpl.content = committmpl.content.replace('{' + j + '}', nodeList[i].innerText)
        }
        committmpl.content = this.delSpecialChar(committmpl.content)
        sendphone = phoneFilterChats(sendphone)
        let patrn = /^\d+$/
        if (!patrn.exec(sendphone)) {
          this.$message({
            showClose: true,
            message: this.$t('sms.phonenumerror'),
            type: 'error',
            duration: 1000
          })
          return
        }
        if (this.cursmstemplate.signname === '') {
          this.$message({
            showClose: true,
            message: this.$t('sms.sendphonenameerror'),
            type: 'error',
            duration: 1000
          })
          return
        }
        this.sendingState = true
        this.$store.dispatch('sendsms', committmpl).then(req => {
          this.sendingState = false
          if (req.success) {
            this.form.smsPhoneNum = ''
            this.realSmsNum = ''
            this.$store.commit('call/SET_CALL_NUM', '')
            this.$message({
              showClose: true,
              message: this.$t('sms.sendsuccess'),
              type: 'success',
              duration: 1000
            })
          } else {
            this.$message({
              showClose: true,
              message: this.$t('sms.sendfail'),
              type: 'error',
              duration: 1000
            })
          }
          if (this.closedSms) { // 若不勾选发送后关闭窗口
            this.$emit('smsWindowSatus', false)
          }
        })
      },
      delSpecialChar (content) {
        content = content.replace(/\\'/g, "'")
        content = content.replace(/\\"/g, '"')
        let contentarr = content.split('"')
        let str = ''
        let str2 = ''
        for (var j = 0; j < contentarr.length - 1; j++) {
          str += contentarr[j] + (j % 2 ? '”' : '“')
        }
        str += contentarr[j]
        contentarr = str.split("'")
        for (var m = 0; m < contentarr.length - 1; m++) {
          str2 += contentarr[m] + (m % 2 ? '’' : '‘')
        }
        str2 += contentarr[m]
        let reg1 = new RegExp('<[^<]*>', 'gi')
        str2 = str2.replace(reg1, '')
        let reg2 = new RegExp('</', 'gi')
        str2 = str2.replace(reg2, '')
        if (str2.substr(str2.length - 1, 1) === '\\' && str2.substr(str2.length - 2, 2) !== '\\\\') {
          str2 = str2 + '\\'
        }
        return str2
      },
      changeout (option) { // 选择短信模板时
        for (let k = 0; k < this.smsTemplates.length; k++) {
          if (this.smsTemplates[k].num === option) {
            this.cursmstemplate = this.smsTemplates[k]
            if (this.cursmstemplate.smsChannel.length === 1) {
              let smsChan = this.cursmstemplate.smsChannel[0]
              this.smsChannels.forEach(item => {
                if (item._id === smsChan) { // 根据id取短信通道配置中的短信最大字数限制，默认是280
                  this.maxWordNum = item.maxWordNum || 280
                }
              })
            } else {
              this.maxWordNum = this.$store.state.sms.textCount || 280
            }
            document.getElementById('smsWrapPane').getElementsByClassName('warn-text')[0].style.display = 'none'
            document.getElementById('smsWrapPane').getElementsByClassName('warn-text2')[0].style.display = 'none'
          }
        }
      },
      reset () { // 重置
        Object.assign(this.form, form)
        let nodeList = document.getElementsByClassName('smsTemplateVar')
        for (let i = 0; i < nodeList.length; i++) {
          nodeList[i].innerText = ''
        }
        // 点击短信的重置的时候，把短信计数隐藏
        document.getElementById('smsWrapPane').getElementsByClassName('warn-text')[0].style.display = 'none'
        document.getElementById('smsWrapPane').getElementsByClassName('warn-text2')[0].style.display = 'none'
        this.$store.commit('call/SET_CALL_NUM', '')
        this.realSmsNum = ''
        this.closedSms = true
      },
      changeData (event) {
        this.$data.form.smsTemplateVar1 = event.srcElement.innerText
      },
      updateSmsNum () {
        let pane = document.getElementById('smsContentPane')
        let paneWrap = document.getElementById('smsWrapPane')
        if (pane) {
          let span = pane.getElementsByClassName('smsTemplateVar')
          if (span) {
            let self = this
            for (var j = 0; j < span.length; j++) {
              span[j].onkeyup = function (cur) {
                self.$store.dispatch('getCache', {type: 'smsSign', id: self.cursmstemplate.sign}).then(curSign => {
                  let content = self.cursmstemplate.content
                  let textCount = Number(self.maxWordNum)
                  let smsSplitBaseNum = self.smsSplitNum
                  let sign = curSign.name
                  let signLen = sign ? sign.length : 0
                  let varLength = self.cursmstemplate.vars * 3
                  let nodeList = paneWrap.getElementsByClassName('smsTemplateVar')
                  let fenzi = paneWrap.getElementsByClassName('fenzi')
                  let fenmu = paneWrap.getElementsByClassName('fenmu')
                  let pagingNum = paneWrap.getElementsByClassName('pagingNum')
                  let inputCount = 0
                  paneWrap.getElementsByClassName('warn-text')[0].style.display = 'block'
                  for (let i = 0; i < nodeList.length; i++) {
                    let lastStr = replaceHtmlToStr(nodeList[i].innerHTML)
                    if (lastStr.length < nodeList[i].innerHTML.length) { // 说明内容中包含html，去除html
                      nodeList[i].innerHTML = lastStr
                    }
                    inputCount += nodeList[i].innerText.length
                  }
                  if (fenzi && fenzi.length > 0) {
                    let fenziNum = textCount - signLen + varLength - content.length - inputCount
                    let curElement = cur.srcElement
                    if (fenziNum < 0) {
                      curElement.innerText = curElement.innerText.substr(0, curElement.innerText.length + fenziNum)
                      inputCount = inputCount + fenziNum
                      fenziNum = 0
                    }
                    fenzi[0].innerText = fenziNum
                  }
                  if (fenmu && fenmu.length > 0) {
                    fenmu[0].innerText = textCount - signLen
                  }
                  if (pagingNum && pagingNum.length > 0) {
                    if ((inputCount + content.length - varLength + signLen) > smsSplitBaseNum) {
                      let n = 1
                      let nc = parseInt((inputCount + content.length - varLength + signLen - smsSplitBaseNum) / smsSplitBaseNum)
                      let nv = (inputCount + content.length - varLength + signLen - smsSplitBaseNum) % smsSplitBaseNum
                      n += nc
                      if (nv > 0) {
                        n += 1
                      }
                      pagingNum[0].innerText = n
                      paneWrap.getElementsByClassName('warn-text2')[0].style.display = 'block'
                    } else {
                      pagingNum[0].innerText = 1
                    }
                  }
                })
              }
            }
          }
        }
      }
    },
    beforeMount () {
      this.$store.dispatch('getCache', {type: 'smsChannel'}).then(res => { // 取短信通道配置
        this.smsChannels = res
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .send-sms
    color $cf-gray1
    font-size 12px
    .icon-question:after
      icon-ques()
    >p
      line-height 2.5
    .warn-text
      line-height 2
      display none
    .warn-text2
      line-height 1.5
      margin-bottom 10px
      display none
  .send-btn
    display block
    background-color $c-main
    width 44px
    height 30px
    line-height 30px
    text-align center
    color $cf-white
    float right
    cursor pointer
  .disabled-btn
    background-color #c1c8d3
  .input-wrap
    margin-top 20px
    bors(1px,$c-main)
    border-radius 2px
    position relative
    .icon-dianhua
      font-size 24px
      height 30px
      line-height 30px
      text-align center
      color $cf-white
      .dialout_button_wrap
        position absolute
        right 0
        top -1px
        cursor pointer
        background-color $c-main
        width 44px
        height 32px
  .input-wrap input
    height 30px
    width 250px
    border 0
    padding-left 4px
    font-size 12px
  #smsContentPane
    padding-top $padding10
  .smscheck-btn
    color $cf-gray4
    margin 10px 0
  .sms-reset
    margin 0 20px 0 46px
  .sms-closed
    margin-right 20px
  .sms-tem
    line-height 2
    word-break break-all
  .sms-select-option
    max-width 500px
    height auto
    word-wrap break-word
    white-space normal
    line-height 20px
    padding 10px 20px
  .pagingNum
    color $c-main
  .fenzi
    color $c-sub
  .fenmu
    color #f08294
  .warp-pre
    word-wrap break-word
    white-space normal
    line-height 24px
  .send-sms >p.sign-name
    line-height 1
    margin-top 10px
  .sms-select-option.selected
    .sms-title-b
      color $cf-color1
  .sms-title-b
    color $cf-gray0
</style>
